'use strict';

const { getDataByText } = require('../utils/utils');

class Market {
  constructor(requestReptile) {
    this.requestReptile = requestReptile;
  }

  async zdfb() {
    const url = 'http://q.10jqka.com.cn/api.php?t=indexflash&';
    const res = await this.requestReptile(url, 'json');
    const { zdfb_data: { zdfb, dnum, znum }, zdt_data: { last_zdt: { dtzs, ztzs } } } = res;
    const arr = ['跌停~-8%', '-6%~-8%', '-4%~-6%', '-2%~-4%', '0-2%', '0~2%', '2%~4%', '4%~6%', '6%~8%', '8%~涨停'];
    return {
      dNum: dnum,
      zNum: znum,
      fb: zdfb.map((value, index) => ({
        value,
        field: arr[index]
      })),
      dtNum: dtzs,
      ztNum: ztzs
    };
  }

  // 市场量能
  async scln() {
    const market = ['1.000001', '0.399001'];
    const data = [];
    const map = {
      f43: 'zxj',
      f47: 'cjl',
      f48: 'cje',
      f57: 'code',
      f58: 'name',
      f168: 'hsl',
      f169: 'zde',
      f170: 'zdf',
    };

    for await (const code of market) {
      const url = `http://push2.eastmoney.com/api/qt/stock/get?fltt=2&fields=f57,f58,f107,f43,f168,f169,f170,f47,f48,f162,f116&secid=${code}&ut=13697a1cc677c8bfa9a496437bfef419&cb=callback&_=1599045294055`;
      const res = await this.requestReptile(url, 'text');
      const item = getDataByText(
        res,
        { data: 'data', },
        'data.data',
        'callback'
      );

      data.push(Object.keys(map).reduce((obj, key) => ({
        ...obj,
        [map[key]]: item[key]
      }), {}));
    }

    return data;
  }
}

module.exports = Market;
